package com.yxh.bigdata.mapreduce.fensi;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SharedFriendsStepOne {

    static class  SharedFriendsOneMapper extends Mapper<LongWritable, Text, Text, Text> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split(":");
            String name = split[0];
            String[] split1 = split[1].split(",");
            for(String s : split1){
                context.write(new Text(s), new Text(name));
            }

        }
    }


    static class SharedFriendsOneReducer extends Reducer<Text, Text, Text, Text>{

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            List<String> personList = new ArrayList<>();
            values.forEach(text -> {
                personList.add(text.toString());
                System.out.println(text.toString());
            });

            for(String p1 : personList){
                for(String p2 : personList){
                    if(p1.equals(p2)){
                        continue;
                    }
                    context.write(new Text(p1 + "-" + p2), key);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        job.setJarByClass(SharedFriendsStepOne.class);

        job.setMapperClass(SharedFriendsOneMapper.class);
        job.setReducerClass(SharedFriendsOneReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        //指定job的输入原始文件所在目录
        FileInputFormat.setInputPaths(job, new Path("D:\\bigdata\\fensi\\input"));
        //指定job的输出结果所在目录
        FileOutputFormat.setOutputPath(job, new Path("D:\\bigdata\\fensi\\output1"));

        boolean res = job.waitForCompletion(true);
        System.exit(res?0:1);
    }
}
